let moment = require('moment');
var Bangbangtang = function() {
  let win = new BrowserWindow({
    width: 400,
    height: 300,
    show: false });
  const ses = win.webContents.session;
  let ips = '';
  let user_urls = [{}];
  let ip_index = 0;
  let user_index = 0;
  let is_batch = 0;
  this.runWithSingleUser = function(user_link) {
    console.log('run single');
    let url_template = 'http://cn.battleofballs.com/share?type=1&id=';
    ips = getProxyIPs();

    is_batch = 0;
    ip_index = 0;
    user_index = 0;

    ses.setProxy({
      proxyRules: ''
    }, function() {
      let p = getOriginUrl(user_link)
      p.then(function(result) {
        let user_id = result.user_id;
        user_urls[0].user_url = 'http://cn.battleofballs.com/share?type=1&id=' + user_id;
        visitUrl(ips[ip_index ++], user_urls[0].user_url);
      });
    });
  }

  this.runWithBatchUsers = function(user_arr) {
    console.log('run batch');
    console.log(user_urls);
    ips = getProxyIPs();
    is_batch = 1;
    ip_index = 0;
    // user_index = 0;
    if (user_index >= user_urls.length) {
      user_index = 0;
    }
    user_urls = user_arr;
    console.log(user_index);
    console.log('开始刷用户' + user_urls[user_index].user_url);
    visitUrl(ips[ip_index ++], user_urls[user_index].user_url);
  }

  this.pause = function() {
    win.webContents.stop();
  }

  this.stop = function() {
    ip_index = 0;
    user_index = 0;
    win.webContents.stop();
  }

  this.getSes = function() {
    return ses;
  }
  function getProxyIPs() {
    let proxy_ip_list = low('db.json').get('proxy_ip').value();
    let ips = proxy_ip_list.map(function(proxy_ip_obj) {
      return proxy_ip_obj.ip + ':' + proxy_ip_obj.port;
    });
    return ips;
  }

  function visitUrl(ip, url) {
    console.log('当前IP：' + ip);
    ses.setProxy({
      proxyRules: 'http=' + ip
    }, function() {
      win.loadURL(url);
    });
  }

  function getAllUserUrls() {
    let user_info = low('db.json').get('user_info').value();
    return user_info;
  }

  function updateRemoteStatus(user_url, status) {
    console.log('更新用户状态');
    let now_time = moment().format('YYYY-MM-DD HH:mm:ss');
    low('db.json').get('user_info').find({user_url: user_url}).assign({status: status, status_time: now_time}).value();
    let ipcRenderer = nodeRequire('electron').ipcRenderer;
    ipcRenderer.send('refresh_user_list','');
    return new Promise(function (resolve, reject) {
      resolve();
    });
  }

  win.webContents.on('did-fail-load', ()=> {
  console.log('fail load');
  });
  win.webContents.on('did-start-loading', ()=> {
    console.log('start load');
  });
  // win.webContents.on('did-stop-loading', ()=> {
  //   console.log('stop load');
  //   console.log(win.webContents.isLoading());
  // });
  win.webContents.on('did-finish-load', ()=> {
    console.log('finish load');
    win.webContents.executeJavaScript(`
        let pre = document.getElementsByTagName('pre');
        if(pre.length == 0) {
          //window.location.reload();
        } else {
          pre[0].innerHTML;
        }
      `, (result)=> {
      if(result == 'ok') {
        console.log('%c ok', 'color: #00CC00');
      } else if (result == 'db error') {
        console.log('%c db error', 'color: #CC0000');
      } else if(result == 'day over') {
        console.log('%c day over', 'color: #CC6600');
        ses.setProxy({
          proxyRules: ''
        }, function() {
          let p = updateRemoteStatus(user_urls[user_index].user_url, '本日完');
          p.then(function() {
            win.webContents.stop();
            if(is_batch) {
              ip_index = 0;
              user_index ++;
              if(user_index < user_urls.length) {
                visitUrl(ips[ip_index], user_urls[user_index].user_url);
              }
            }
          });
        });
        return;
      } else if(result == 'week over') {
        console.log('%c week over', 'color: #CC6600');
        ses.setProxy({
          proxyRules: ''
        }, function() {
          let p = updateRemoteStatus(user_urls[user_index].user_url, '本周完');
          p.then(function() {
            win.webContents.stop();
            if(is_batch) {
              ip_index = 0;
              user_index ++;
              if(user_index < user_urls.length) {
                visitUrl(ips[ip_index], user_urls[user_index].user_url);
              }
            }
          });
        });
        return;
      } else {
        console.log('%c ' + result, 'color: #6699FF');
        win.webContents.stop();
        win.webContents.loadURL(user_urls[user_index].user_url);
        return;
      }

      if(ip_index < ips.length) {
        visitUrl(ips[ip_index ++], user_urls[user_index].user_url);
      } else {
        console.log('执行结束');
        ip_index = 0;
        user_index ++;
        if(is_batch == 1 && user_index < user_urls.length) {
          console.log('完成刷用户' + user_urls[user_index].user_url);
          runWithBatchUsers();
        } else {
          console.log('总进程结束');
        }
      }
    });
  });
}

module.exports = Bangbangtang;

function getOriginUrl(url) {
  return new Promise(function(resolve, reject) {
    $.post('http://dwz.cn/query.php', {tinyurl: url}, function(result) {
      let long_url = JSON.parse(result).longurl;
      let user_id = getParam(long_url).id;
      let user_url = 'http://cn.battleofballs.com/share?type=1&id=' + user_id;
      resolve({user_url: user_url, user_id: user_id});
    });
  });
}

function getParam(url) {
  let result = {};
  var num=url.indexOf("?")
  let str=url.substr(num+1); //取得所有参数   stringvar.substr(start [, length ]

  var arr=str.split("&"); //各个参数放到数组里
  for(var i=0;i < arr.length;i++){
    num=arr[i].indexOf("=");
    if(num>0){
      name=arr[i].substring(0,num);
      value=arr[i].substr(num+1);
      result[name]=value;
    }
  }
  return result;
}
